package com.question.service.impl;

import com.question.exception.BaseException;
import com.question.mapper.CategoryMapper;
import com.question.mapper.QuestionMapper;
import com.question.pojo.entity.Category;
import com.question.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private QuestionMapper questionMapper;

    /**
     * 获取所有分类
     *
     * @return
     */
    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectAllCategories();
    }

    @Override
    public Category getCategoryById(Integer categoryId) {
        return categoryMapper.getCategoryById(categoryId);
    }

    @Override
    @Transactional
    public void addCategory(Category category) {
        categoryMapper.insertCategory(category);
    }

    @Override
    @Transactional
    public void updateCategory(Category category) {
        categoryMapper.updateCategory(category);
    }

    @Override
    public List<Category> getCategoriesByMajorId(Integer majorId) {
        return categoryMapper.selectCategoriesByMajorId(majorId);
    }

    @Override
    @Transactional
    public void deleteCategory(Integer categoryId) {
        // 检查是否有题目关联该分类
        int questionCount = questionMapper.countQuestionsByCategory(categoryId);
        if (questionCount > 0) {
            throw new BaseException("该分类下存在题目，无法删除");
        }

        categoryMapper.deleteCategory(categoryId);
    }

    @Override
    public int countQuestionsByCategory(Integer categoryId) {
        return questionMapper.countQuestionsByCategory(categoryId);
    }

    @Override
    public int countCategoriesByMajor(Integer majorId) {
        return categoryMapper.countByMajorId(majorId);
    }
}